﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web.Security;
using System.Diagnostics;


namespace One.Framework.UI.Security
{
    public class MachineKeyCryptography
    {
        public static string Encode(string text, CookieProtection cookieProtection)
        {
            if (string.IsNullOrEmpty(text) || cookieProtection == CookieProtection.None)
                return text;
            else
            {
                byte[] buf = Encoding.UTF8.GetBytes(text);

                MachineKeyProtection m = MachineKeyProtection.All;
                switch (cookieProtection)
                {
                    case CookieProtection.Encryption: m = MachineKeyProtection.Encryption; break;
                    case CookieProtection.Validation: m = MachineKeyProtection.Validation; break;
                }

                return MachineKey.Encode(buf, m);
            }
        }

        public static string Decode(string text, CookieProtection cookieProtection)
        {
            if (string.IsNullOrEmpty(text) || cookieProtection == CookieProtection.None)
                return text;
            else
            {
                byte[] buf;
                try
                {
                    buf = CookieProtectionHelperWrapper.Decode(cookieProtection, text);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("Unable to decode the text : " + text, ex.InnerException);
                }

                if (buf == null || buf.Length == 0)
                {
                    throw new InvalidOperationException("Unalbe to decode the text : " + text);
                }

                return Encoding.UTF8.GetString(buf, 0, buf.Length);
            }
        }
    }
}
